package org.microdream.easy.deploy.action;

import ice.server.comm.BaseAction;
import ice.server.comm.GloubCode;
import ice.server.comm.ParamBulider;
import ice.tool.ResultMap;
import ice.tool.bean.BeanUtil;
import org.apache.commons.lang3.StringUtils;
import org.microdream.easy.deploy.po.DGroup;
import org.microdream.easy.deploy.service.DGroupService;
import org.microdream.easy.deploy.service.DSequenceService;
import org.microdream.easy.deploy.utils.ListUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("DGroup")
public class DGroupAction extends BaseAction {

    @Resource
    private DGroupService dGroupService;
    @Resource
    private DSequenceService dSequenceService;

    @PostMapping("/searchByPage")
    public Map searchByPage(Integer limit, Integer offset){
        if(limit==null || offset==null){
            return null;
        }
        return dGroupService.searchByPage(ParamBulider.build().addEqual("rows", limit).addEqual("page", offset / limit).get());
    }

    @PostMapping("")
    public Map add(DGroup dGroup){
        dGroup.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        dGroup.setIsDelete(0);
        dGroup.setGroupCode(dSequenceService.getNextSequence(GloubCode.GROUPCODE.getName(),GloubCode.SUPPLEMENTCODE.getName()));
        return dGroupService.add(dGroup);
    }

    @PutMapping("")
    public Map update(DGroup dGroup){
        DGroup dGroupOld = new DGroup();
        try {
            BeanUtil.copyNotEmptyProprties(dGroup,dGroupOld);
            dGroupOld.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        } catch (Exception e) {
            return ResultMap.build().warningState().message(e.getMessage()).get();
        }
        return dGroupService.upd(dGroupOld);
    }

    @DeleteMapping("/{key}")
    public Map delete(@PathVariable("key")String key){
        if(StringUtils.isEmpty(key)){
            return ResultMap.build().warningState().message("无效数据").get();
        }
        List<String> ids = Arrays.asList(key.split(","));
        return dGroupService.del(ListUtil.StringToInteger(ids));
    }

    @GetMapping("/{key}")
    public DGroup searchById(@PathVariable("key") Integer key){
        return dGroupService.get(key);
    }
}
